import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtAvatar, AtButton, AtIcon, AtInput, AtList} from 'taro-ui'
import {Image, Input, Navigator, Picker, View} from '@tarojs/components'
import WxValidate from '../../../utils/wx-validate'
import {http} from '../../../utils/http'
import {vcmonitor} from "../../../utils/tools";
import {
  BASE_URL,
  GET_PERSON_INFO,
  RESOURCE_URL,
  SYSTEM_UPLOAD,
  TARO_ENV,
  UPDATE_PERSON_INFO
} from '../../../constants/api'
import {user} from '../../../utils/user.service'
import {PersonInfo} from '../../../utils/server.interface'
import {h5Wx} from "../../../utils/h5.service";
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import {lxH5Wx} from "../../../utils/lx.h5.service";
import './setting.scss'

interface FormData {
  nick_name: string
  user_face: string
  photo: string
  real_name: string
  phone: string
  identify_num: string
  address: string
  delivery_province: string
  delivery_city: string
  delivery_area: string
  birthday: string
  company: string
}

export default class Setting extends Component {
  state: {
    formData: FormData
    openFaceRecognition: any
    errList: {
      real_name: boolean
      phone: boolean
      identify_num?: boolean
      address?: boolean
      delivery_province?: boolean
      delivery_city?: boolean
      delivery_area?: boolean
      birthday?: boolean
      company?: boolean
    }
    submiting: boolean
  } = {
    openFaceRecognition: false,
    formData: {
      nick_name: '',
      user_face: '',
      real_name: '',
      phone: '',
      identify_num: '',
      address: '',
      photo: '',
      delivery_province: '',
      delivery_city: '',
      delivery_area: '',
      birthday: '',
      company: '',
    },
    errList: {
      real_name: false,
      phone: false,
    },
    submiting: false
  }

  async UNSAFE_componentWillMount() {
    vcmonitor(this)
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    if (!(await user.checkLogin())) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none'
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
    await Taro.showLoading({title: '加载中...'})
    const info: any = await http.get<PersonInfo>(GET_PERSON_INFO, {})
    if (info) {
      const {
        openFaceRecognition,
        user_face,
        real_name,
        phone,
        photo,
        identify_num,
        address,
        delivery_province,
        delivery_city,
        delivery_area,
        birthday,
        nick_name,
        company
      } = info
      this.setState({
        openFaceRecognition,
        formData: {
          user_face,
          real_name,
          phone,
          photo,
          nick_name,
          identify_num,
          address,
          delivery_province,
          delivery_city,
          delivery_area,
          birthday,
          company
        }
      })
    }
    Taro.hideLoading()
  }

  async componentDidShow() {
    await Taro.setNavigationBarTitle({
      title: '账户管理'
    })
    const {formData} = this.state
    if (process.env.TARO_ENV === 'h5') {
      formData['user_face'] = Taro.getStorageSync('faceUrl')
      this.setState({formData})
    } else {
      if (Taro.getCurrentInstance().page.data.face_url) {
        formData['user_face'] = Taro.getCurrentInstance().page.data.face_url
        this.setState({formData})
      }
    }
  }

  inputChange(type, value) {
    const oldData = this.state.formData
    if (type == 'birthday') {
      oldData[type] = value.detail.value
    } else {
      oldData[type] = value
    }
    this.setState({formData: oldData})
  }

  regionChange(e) {
    const oldData = this.state.formData
    const area = e.detail.value
    oldData['delivery_province'] = area[0]
    oldData['delivery_city'] = area[1]
    oldData['delivery_area'] = area[2]
    this.setState({formData: oldData})
  }

  rules = {
    real_name: {
      required: true,
      minlength: 2
    },
    phone: {
      tel: true
    }
  }
  message = {
    real_name: {
      required: "姓名不能为空",
      minlength: "姓名不能小于2个字符"
    },
    phone: {
      tel: "手机号码不正确"
    }
  }

  submit() {
    const {formData} = this.state
    if (formData.identify_num) {
      const reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
      if (!reg.test(formData.identify_num)) {
        Taro.showToast({title: '身份证格式错误', icon: 'none'})
        return
      }
    }
    this.setState({submiting: true}, async () => {
      const validate = new WxValidate(this.rules, this.message)
      if (!validate.checkForm(formData)) {
        const oldData = this.state.errList
        if (validate && validate.errorList && validate.errorList[0].param) {
          oldData[validate.errorList[0].param] = true
          Taro.showToast({
            title: validate.errorList[0].msg,
            icon: 'none'
          })
        }
        this.setState({errList: oldData, submiting: false})
        return false;
      }
      const ret = await http.post(UPDATE_PERSON_INFO, {...formData})
      if (ret) {
        Taro.showToast({title: '保存成功'})
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.switchTab({url: '/pages/my/index/index'})
        }, 1500)
      } else {
        this.setState({submiting: false})
      }
    })
  }

  onChooseAvatar = async (e)=> {
    const {formData} = this.state
    const {avatarUrl} = e.detail
    Taro.uploadFile({
      url: BASE_URL + SYSTEM_UPLOAD,
      filePath: avatarUrl,
      name: 'file',
      header: http.getHeader(),
      success: (res)=>{
        formData['photo'] = JSON.parse(res.data).data
        this.setState({
          formData
        })
      },
      fail () {
        Taro.showToast({ title: '上传图片失败' })
      }
    })
  }

  nickNameChange(e){
    const oldData = this.state.formData
    oldData['nick_name'] = e.detail.value
    this.setState({formData: oldData})
  }

  handlerChooseAvatar() {
    if (process.env.TARO_ENV === 'tt') return false
    lxH5Wx.chooseImage(async (f, length) => {
      lxH5Wx.uploadFile(f, length, (data) => {
        const {formData} = this.state
        formData['photo'] = data
        this.setState({
          formData
        })
      })
    }, 0)
  }

  getHeadImage(image) {
    if (!image) {
      return ''
    }
    if (!image.startsWith('http')) {
      image = RESOURCE_URL + image
    }
    return image
  }

  render() {
    const {openFaceRecognition, errList, formData, submiting} = this.state
    return (
      <View className='my-setting-root'>
        <GzhAuth />
        <View className='user-box'>
          <View className='user-box-input'>
            <View className='header-img'>
              <View className='header-title'>头像</View>
              <View className='img-box'>
                {TARO_ENV === 'weapp' ? <button open-type='chooseAvatar' bindchooseavatar={this.onChooseAvatar} onChooseAvatar={this.onChooseAvatar}>
                  <Image className='img' src={this.getHeadImage(formData.photo || RESOURCE_URL + "/resources/weapp/images/headimg.png")} />
                </button> :
                  <Image className='img' onClick={this.handlerChooseAvatar.bind(this)} src={this.getHeadImage(formData.photo || RESOURCE_URL + "/resources/weapp/images/headimg.png")} />
                }
              </View>
            </View>
            <View className='name-box'>
              <View className='text'>昵称</View>
              <Input value={formData.nick_name} type='nickname' disabled={process.env.TARO_ENV === 'tt'} onChange={this.nickNameChange.bind(this)} maxLength={15} className='nickName'
                placeholder='请输入昵称'
              />
            </View>
            <AtInput error={errList.real_name} maxLength={15} onChange={this.inputChange.bind(this, 'real_name')}
              name='real_name' title='姓名' value={formData.real_name || ''} placeholder='请填写姓名'
            />
            <AtInput className='phone' border={false} error={errList.phone}
              onChange={this.inputChange.bind(this, 'phone')} name='phone' title='手机号'
              value={formData.phone || ''}
              placeholder='请填写手机号码'
            />
            <Picker mode='date' className='picker' onChange={this.inputChange.bind(this, 'birthday')}>
              <AtList>
                <View className='at-input'>
                  <View className='at-input__container'>
                    <View className='at-input__title'>出生日期</View>
                    <View className='at-input__input'>{formData.birthday ? formData.birthday : ''}</View>
                  </View>
                </View>
              </AtList>
            </Picker>
            <AtInput error={errList.identify_num} maxLength={18} onChange={this.inputChange.bind(this, 'identify_num')}
              name='identify_num' title='身份证' value={formData.identify_num || ''} placeholder='请填写身份证'
            />
            {!!openFaceRecognition &&
            <Navigator className='goaddlist face_list' url='/main/my/face/face' hoverClass='none'>
              <View className='label face_label'>
                人脸采集
                <View className='face_label_tips'>用于人脸识别核验</View>
              </View>
              <View className='face_right'>
                {formData.user_face && <AtAvatar image={formData.user_face} circle />}
                <AtIcon value='chevron-right' size='16' color='#666' />
              </View>
            </Navigator>}
            <AtInput border={false} error={errList.identify_num} onChange={this.inputChange.bind(this, 'company')}
              name='company' title='单位名称' value={formData.company || ''} placeholder='请填写单位名称'
            />
            <Navigator className='goaddlist' url='/other/address/index?my=true' hoverClass='none'>
              <View className='label'>我的收货地址</View>
              <AtIcon value='chevron-right' size='16' color='#666' />
            </Navigator>
          </View>
        </View>
        <View className='btn-box'><AtButton type='primary' loading={submiting} disabled={submiting}
          onClick={this.submit.bind(this)}
        >保存</AtButton></View>
      </View>
    )
  }
}
